import { _decorator, Component, Node ,director, log, AudioClip, Label, find, sys, CCObjectFlags, Prefab, instantiate, Color, resources, game } from 'cc';
import { AudioManager } from './AudioManager';
import { PlayerManager } from './PlayerManager';


const { ccclass, property } = _decorator;

@ccclass('GameManager')
export class GameManager extends Component {
    // 静态实例，确保全局唯一
    private static _instance: GameManager = null;
    // 游戏是否结束标志，0是表示未开始 ,1 表示进行中，2 表示结束
    private _gameStatus: number = 0;
    // 难度
    private _difficulty: number = 1;
    
    //加载预制体
    @property({ type: Prefab,tooltip: "方块预制体" })
    boxPrefab: Prefab | null = null; 
    
    //方块合集
    private _boxs: number[] = [];
    //当前位置
    private _currentPos: number = 0;


    //加载节点
    @property({ type: Node, tooltip: "玩家节点" })
    playerNode: Node | null = null;


    // 单例访问器
    public static get instance(): GameManager {
        return this._instance;
    }
    
    onLoad() {
        if (GameManager._instance === null) {
            GameManager._instance = this;
            director.addPersistRootNode(this.node);
        } else {
            // 如果已存在实例，销毁当前节点
            this.node.destroy();
        }
    }
    
    start() {
        console.log("GameManager初始化完成");
        this.initGame();
         AudioManager.instance.playBGM('sound/bg');
    }
    // 退出游戏
    public exitGame() {
        log("exitGame");
        if (sys.isNative) {
            // 退出游戏
            game.end();
            // director.end();
        } else {
            // 退出游戏
            window.history.back();
        }
    }
    /**
     * 初始化游戏
     */
    public initGame() {


        this._gameStatus = 0;
        this._boxs=[];
        this.playerNode.setPosition(0,0,0);
        this._currentPos=0;

        let boxNode = find("Canvas/boxs");
        boxNode.removeAllChildren();

        let node = find("Canvas/player/Camera/ui/Label");
        node.getComponent(Label).string = "分数：" + this._currentPos;
       


        let nodeEnd = find("Canvas/uiEnd");
        nodeEnd.active = false;
        let nodeStart = find("Canvas/uiStart");
        nodeStart.active = true;
        //批量生成预制体
        this.generateBox(50);
    }
    //生成预制体
    protected generateBox(num: number) {
        let arr = [1];
        for (let i = 1; i <= (num-2); i++) {
            if (arr[i-1] === 0) {
                arr.push(1); 
            } else {
                arr.push(Math.random() < 0.5 ? 0 : 1); 
            }
        }
        arr.push(1);
        this._boxs = arr;
        for (let i = 0; i <= this._boxs.length; i++) {
            
            if(this._boxs[i] === 1){
                let box = instantiate(this.boxPrefab);
                let node = find("Canvas/boxs");
                // log(box,node);
                box.parent = node;
                box.x = i * 80;
                // log( box.x);
                // box.setPosition(i * 80,0, 0);
            }
        }
        

    }
     

    public paying(event: Event, customEventData: string) {
        log("paying",event,customEventData);
        this._difficulty = parseInt(customEventData);
      
        this._gameStatus = 1;
        let nodeEnd = find("Canvas/uiEnd");
        nodeEnd.active = false;
        let nodeStart = find("Canvas/uiStart");
        nodeStart.active = false;
    }

    public jumpStart(event: Event, customEventData: string) {
        log("jumpStart");
        if(this._gameStatus !== 1) return
        let num = parseInt(customEventData);
        
        this.playerNode.getComponent(PlayerManager).jump(num);
    }
    public jumpEnd(num:number) {
        this._currentPos+= num;
        log("jumpEnd",this._currentPos);

        let node = find("Canvas/player/Camera/ui/Label");
        node.getComponent(Label).string = "分数：" + this._currentPos;
        
        if (this._boxs[this._currentPos] === 0) {
            this.initEnd(0);
            return;
        }
        if (this._currentPos >= this._boxs.length) {
            this.initEnd(1);
            return;
        }
    }

    public initEnd(num: number) {
        log("initEnd");
        this._gameStatus = 3;
        let nodeEnd = find("Canvas/uiEnd");
        nodeEnd.getChildByName('Label').getComponent(Label).string = num === 0 ? "游戏失败" : "游戏成功";
        nodeEnd.active = true;

        let nodeStart = find("Canvas/uiStart");
        nodeStart.active = false;
        this.unscheduleAllCallbacks();
    }
    
}


